import { fetchAll, fetchVersion } from '@/api/sys/dictionary'

const state = {
  dictionaries: [],
  version: {}
}

const mutations = {
  SET_DICTIONARIES: (state, dictionaries) => {
    state.dictionaries = dictionaries
  },
  SET_VERSION: (state, version) => {
    state.version = version
  }
}

const actions = {
  setDictionaries({ commit }, uid) {
    return new Promise((resolve, reject) => {
      fetchAll({ uid: uid })
        .then(response => {
          const { result } = response
          if (!result) {
            reject('dictionaries fetch failed')
          }
          let list = []
          result.forEach(dict => {
            const d = {
              dictGroup: dict.dictGroup,
              text: dict.text,
              value: dict.text, // 该字段用于DictGroupInput组件
              code: dict.code,
              textColor: dict.textColor,
              reserved1: dict.reserved1,
              reserved2: dict.reserved2
            }
            list = [...list, d]
          })

          commit('SET_DICTIONARIES', list)
          resolve(result)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  setVersion({ commit }) {
    return new Promise((resolve, reject) => {
      fetchVersion()
        .then(response => {
          const { result } = response
          if (!result) {
            reject('dictionaries fetch failed')
          }

          commit('SET_VERSION', result)
          resolve(result)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
